﻿@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject IDataCacheService _dataCatcheService
@inject IStructuredDataService _structuredDataService
@inject IPopupService PopupService
@inject IEventService _eventService
@inject IPopupService PopupService
@implements IDisposable

@if (string.IsNullOrWhiteSpace(EntryView.Name) == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="@(EntryView.Name)" Description="@EntryView.BriefIntroduction" Image="@EntryView.MainPicture" />
}
else
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip />
}



@if (isNotFound)
{
    <NotFoundCard>
        <h1 class="text-center title-large">找不到这个词条哦......</h1>
        <div class="text-center">可以在这里<a href="/entries/establishentry">创建词条</a>，也可以查看<a href="/articles/index/2">《词条编辑规范》</a></div>
    </NotFoundCard>

}
else
{
    @if (_dataCatcheService.EntryIndexPageCatche.Check(Id) || isReady)
    {
            @switch (style)
            {
                case EntryStyleTemplate.Default:
                    <CnGalWebSite.Shared.Component.Entries.NewVersion.IndexCard EntryView="EntryView" CanDeleted="CanDeleted" OnPreEdit="OnPreEdit" OnRevoke="OnRevoke" />
                    break;
                case EntryStyleTemplate.OfficialWebsite:
                    <CnGalWebSite.Shared.MasaComponent.PC.Entries.Templates.OfficialWebsite.Main.IndexCard Model="EntryView" />
                    break;
                case EntryStyleTemplate.ArticleIntroduce:
                    <CnGalWebSite.Shared.MasaComponent.PC.Entries.Templates.ArticleIntroduce.Main.IndexCard Model="EntryView" />
                    break;
                case EntryStyleTemplate.Magazine:
                    <CnGalWebSite.Shared.MasaComponent.PC.Entries.Templates.Magazine.Main.IndexCard Model="EntryView" />
                    break;
                default:
                    break;
            }
    }
    else
    {
        <CnGalWebSite.Components.Progressings.ProgressingCard Page />
    }

}
@if (isFirstLoad == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.NavLoadingCard IsLoading="isLoading" />
}

<CnGalWebSite.Shared.MasaComponent.Shared.Components.TrackEvent DataType="TrackEventDataType.Entry" EventType="TrackEventType.View" ObjectId="@EntryView.Id.ToString()"
                                                                ObjectName="@EntryView.Name" />

@code {

    [Parameter]
    public string Id { get; set; }
    [Parameter]
    public int Style { get; set; }

    public EntryStyleTemplate style { get; set; }

    public StringNumber TabIndex { get; set; } = 1;

    bool isReady = false;
    bool isLoading = false;
    bool isNotFound = false;
    bool isFirstLoad = true;
    public string CurrentUserRank { get; set; }

    public EntryIndexViewModel EntryView { get; set; } = new EntryIndexViewModel();


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    public bool IsAdmin { get; set; } = false;
    public bool CanDeleted { get; set; }
    string LastLookName = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            NavigationManager.LocationChanged -= LocationChanged;
            NavigationManager.LocationChanged += LocationChanged;

            _eventService.SwitchEntryStyle -= SwitchEntryStyle;
            _eventService.SwitchEntryStyle += SwitchEntryStyle;

            isFirstLoad = false;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }

    public async Task Refresh()
    {
        try
        {
            style = GetStyleTemplate();
            //获取词条信息
            EntryView = await _dataCatcheService.EntryIndexPageCatche.GetCache(Id);
            //判断如果名称为空则返回主页
            if (string.IsNullOrWhiteSpace(EntryView.Name))
            {
                NavigationManager.NavigateTo("/entries/home");
            }

            var userState = await authenticationStateTask;
            var user = userState.User;
            if (user.IsInRole("Editor"))
            {
                IsAdmin = true;
                CanDeleted = true;
            }


            //生成轮播结构数据
            await GenerateCarouselStructuredDataJson();

            isReady = true;
            //StateHasChanged();

        }
        catch (Exception exc)
        {
            isNotFound = true;
            isReady = true;
            StateHasChanged();
        }
    }

    public async Task GenerateCarouselStructuredDataJson()
    {
        var urls = new List<string>();
        urls.AddRange(EntryView.EntryRelevances.Select(s => NavigationManager.BaseUri + "entries/" + s.Id));
        urls.AddRange(EntryView.Roles.Select(s => NavigationManager.BaseUri + "entries/" + s.Id));
        urls.AddRange(EntryView.ProductionGroups.Select(s => NavigationManager.BaseUri + "entries/" + s.Id));
        urls.AddRange(EntryView.StaffGames.Select(s => NavigationManager.BaseUri + "entries/" + s.Id));
        urls.AddRange(EntryView.ArticleRelevances.Select(s => NavigationManager.BaseUri + "articles/" + s.Id));
        await _structuredDataService.SetStructuredData(urls);
    }


    private async Task OnRevoke(Operation operation)
    {
        var ret = await PopupService.ConfirmAsync("确认撤销编辑", "撤销编辑后会删除数据，无法恢复，请谨慎操作");
        if (ret == false)
        {
            return;
        }
        //上传
        try
        {
            var obj = await _httpService.PostAsync<RevokeExamineModel, Result>("api/entries/RevokeExamine", new RevokeExamineModel { Id = EntryView.Id, ExamineType = operation });
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastAsync("撤销审核请求失败", AlertTypes.Error);
            }
            else
            {
                await PopupService.ToastAsync("撤销审核请求成功", AlertTypes.Success);
                //修改各部分编辑状态
                switch (operation)
                {
                    case Operation.EstablishMain:
                        EntryView.MainState = EditState.Normal;
                        break;
                    case Operation.EstablishMainPage:
                        EntryView.MainPageState = EditState.Normal;
                        break;
                    case Operation.EstablishAddInfor:
                        EntryView.InforState = EditState.Normal;
                        break;
                    case Operation.EstablishRelevances:
                        EntryView.RelevancesState = EditState.Normal;
                        break;
                    case Operation.EstablishImages:
                        EntryView.ImagesState = EditState.Normal;
                        break;
                    case Operation.EstablishTags:
                        EntryView.TagState = EditState.Normal;
                        break;
                    case Operation.EstablishAudio:
                        EntryView.AudioState = EditState.Normal;
                        break;
                    case Operation.EstablishWebsite:
                        EntryView.WebsiteState = EditState.Normal;
                        break;
                }
                _dataCatcheService.EntryIndexPageCatche.Clean(Id);
                await Refresh();
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "撤销审核请求失败");
        }
    }

    public void OnPreEdit(bool value)
    {
        EntryView.IsEdit = value;
        StateHasChanged();

    }

    public EntryStyleTemplate GetStyleTemplate()
    {
        if ((EntryStyleTemplate)Style != EntryStyleTemplate.None)
        {
            return (EntryStyleTemplate)Style;
        }
        else if (_dataCatcheService.ThemeSetting.EntryTemplate != EntryStyleTemplate.None)
        {
            return _dataCatcheService.ThemeSetting.EntryTemplate;
        }
        else
        {
            return EntryView.Template == EntryStyleTemplate.None ? EntryStyleTemplate.Default : EntryView.Template;
        }
    }

    public async void SwitchEntryStyle()
    {
        var index = ((int)style + 1) % 5;
        if (index == 0)
        {
            index = 1;
        }
        NavigationManager.NavigateTo(NavigationManager.GetUriWithQueryParameter("style", index));
        await PopupService.ToastAsync($"应用“{((EntryStyleTemplate)index).GetDisplayName()}”样式", AlertTypes.Success);
    }

    public async void LocationChanged(object sender, LocationChangedEventArgs args)
    {

        var tempStyle = GetStyleTemplate();

        //是否需要清空临时样式
        if (NavigationManager.Uri.Contains("entries/index") == false || (style == EntryStyleTemplate.OfficialWebsite && tempStyle != EntryStyleTemplate.OfficialWebsite))
        {
            _eventService.OnCleanTempEffectTheme();
        }

        //是否导航到其他词条
        if (Id != EntryView.Id.ToString())
        {
            if (_dataCatcheService.EntryIndexPageCatche.Check(Id) == false)
            {
                isLoading = true;
                StateHasChanged();
                await Refresh();
                isLoading = false;
                StateHasChanged();
            }
            else
            {
                await Refresh();
                StateHasChanged();
            }
        }
        else
        {
            //尽量减少状态更改次数
            if (style != tempStyle)
            {

                style = tempStyle;
                StateHasChanged();
            }
        }
    }

    #region 释放实例

    public void Dispose()
    {

        NavigationManager.LocationChanged -= LocationChanged;
        _eventService.SwitchEntryStyle -= SwitchEntryStyle;

        GC.SuppressFinalize(this);
    }
    #endregion
}
